<script setup lang="ts">
import { reactive, onMounted, shallowRef } from "vue";
import type { RuleObject } from "ant-design-vue/es/form";
import { Form } from "ant-design-vue";
import { handleApi, handleForm } from "@/utils/alert.ts";
import { getExpressBrands } from "@/api/express.ts";
import { useCache } from "@/stores/cache.ts";
import { updateTrackNumber } from "@/api/waybill.ts";

const { getter } = useCache()
const loading = shallowRef(false)

const props = defineProps<{ order?: IOrder }>()

export type FormState = {
  // 快递公司代码
  logistics_id: string,
  // 快递单号
  tracking_number: string,
}

const emit = defineEmits<{
  (e: 'success'): void;
}>()

const options = shallowRef<ExpressBrand[]>([])

const formState = reactive<FormState>({
  logistics_id: '',
  tracking_number: '',
})
const formRules = reactive<PartialRecord<FormState, RuleObject[]>>({
  logistics_id: [],
  tracking_number: []
})
const { validate, validateInfos } = Form.useForm(formState, formRules)

const onSubmit = async () => {
  const res = await validate().catch(handleForm)
  if (res && props.order?.order_id) {
    loading.value = true
    await updateTrackNumber({
      ...res,
      order_id: props.order.order_id
    }).then(() => emit('success'))
      .catch(handleApi)
      .finally(() => loading.value = false)
  }
}

onMounted(() => {
  loading.value = true
  formState.logistics_id = props.order?.logistics_id || ''
  formState.tracking_number = props.order?.tracking_number || ''
  getter('ExpressBrands', () => getExpressBrands().then(res => res.data))
    .then(brands => options.value = brands || [])
    .catch(handleApi)
    .finally(() => loading.value = false)
})

const expressFilter = (value: string, option: { 'data-item': ExpressBrand }) => {
  const brand = option["data-item"]
  return brand.name.includes(value) || brand.wp_code.includes(value)
}

</script>

<template>
  <ASpin :spinning="loading">
    <AForm layout="horizontal"
           autocomplete="off"
           :label-col="{ span: 4 }"
           :wrapper-col="{ span: 18 }"
           :model="formState"
           @finish="onSubmit">
      <AFormItem label="快递公司" v-bind="validateInfos.logistics_id">
        <ASelect v-model:value="formState.logistics_id" show-search :filter-option="expressFilter">
          <ASelectOption value="">无</ASelectOption>
          <ASelectOption v-for="option of options" :value="option.wp_code" :data-item="option">{{ option.name }}</ASelectOption>
        </ASelect>
      </AFormItem>

      <AFormItem label="快递单号" v-bind="validateInfos.tracking_number">
        <AInput v-model:value="formState.tracking_number"></AInput>
      </AFormItem>

      <AFormItem :wrapper-col="{ offset: 4, span: 18 }">
        <AButton type="primary" html-type="submit">确认</AButton>
      </AFormItem>
    </AForm>
  </ASpin>
</template>